<?php

namespace App\Exceptions;

use App\Http\Enums\HttpResCode;
use Exception;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class Fail extends Exception
{
    public function __construct($message = "", int|HttpResCode $code = 0, $previous = null)
    {
        if ($code instanceof HttpResCode) {
            $code = $code->value;
        }
        parent::__construct($message, $code, $previous);
    }

    /**
     * 报告异常。
     */
    public function report(): bool
    {
        // 不报告！！
        return false;
    }

    /**
     * 报告内容
     */
    public function context(): array
    {
        return ['msg' => $this->getMessage()];
    }

    /**
     * 返回异常为 HTTP 响应。
     */
    public function render(Request $request): JsonResponse
    {
        return new JsonResponse(['code' => $this->getCode() ?: HttpResCode::Fail, 'msg' => $this->getMessage(), 'data' => $request->all()]);
    }
}
